package com.fzq.config.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fzq.util.ResponseResult;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 认证异常处理器，进入到这里说明没有登录
 *
 * 使用场景
 * 当用户访问以下接口时触发：
 *
 * 未登录：访问需要认证的接口（如 /user/profile）。
 * Token 无效/过期：携带无效的 JWT 或 Token 过期。
 * 示例：
 *
 * 前端未携带 Token 访问需要认证的接口。
 * 后端验证 JWT 时发现签名错误或已过期。
 */
@Component
public class SimpleAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request,
                         HttpServletResponse response,
                         AuthenticationException authException) throws IOException, ServletException {
        //返回成功状态码
        ObjectMapper objectMapper=new ObjectMapper();
        ResponseResult<Void> responseResult=new ResponseResult<Void>(6005, "未登录，或token已过期。。。");
        //响应请求转码
        response.setContentType("application/json;charset=UTF-8");

        String json=objectMapper.writeValueAsString(responseResult);

        //输出json字符串到客户端
        PrintWriter printWriter =response.getWriter();
        printWriter.print(json);
        printWriter.flush();
        printWriter.close();

    }
}
